﻿using System;
using System.Collections.Generic;
using System.Linq;
using si.caha.Model;

namespace si.caha.Repository
{
    /// <summary>
    /// Repository class for Category table in database
    /// </summary>
    public class CategoryRepository : BaseRepository
    {
        public CategoryRepository(DataContext dataConext) : base(dataConext){}
        
        public List<Category> GetAll()
        {
            return GetDataContext().Categories.ToList();
        }

        public Category Get(int categoryId)
        {
            return GetDataContext().Categories.SingleOrDefault(c => c.CategoryId == categoryId);
        }

        public Category GetByTitle(string categoryTitle)
        {
            return GetDataContext().Categories.SingleOrDefault(c => c.Title == categoryTitle);
        }

        public Dictionary<string, string> Save(Category entity)
        {
            Dictionary<string, string> errors = ValidateAndGetErrors(entity);
            if (errors.Count == 0)
            {
                if (entity.CategoryId == 0)
                {
                    GetDataContext().Categories.Add(entity);
                }
                else
                {
                    var categoryToUpdate = 
                        GetDataContext().Categories.SingleOrDefault(i => i.CategoryId == entity.CategoryId);

                    //categoryToUpdate = entity;
                    categoryToUpdate.Title = entity.Title;
                    categoryToUpdate.CategoryParentId = entity.CategoryParentId;
                    categoryToUpdate.Level = entity.Level;
                }
                GetDataContext().SaveChanges();
            }
            return errors;
        }

        public string Delete(int CategoryId)
        {
            Category category = Get(CategoryId);
            if (category != null)
            {
                GetDataContext().Categories.Remove(category);
                GetDataContext().SaveChanges();
                return "";
            }
            return "";
        }
    }
}